<?php
namespace Member\Controller;
use Think\Controller;
class OrderController extends CommonController {

    /**
     * 订单列表
     *
     * @return void
     * @author
     **/
    function lists()
    {
         $map['member_id']=$_SESSION['member']['id'];
         $list=D('Admin/order')->where($map)->select();

        //因为存进订单表的时候，是转成字符串存进order_desc字段里面的，使用需要转回来
         foreach ($list as $key => $v) {
            $list[$key]['goods_desc']=json_decode($v['goods_desc'],true);
         }
// print_r($list);die;
         $this->assign('list',$list);
         $this->assign('order_status',C('ORDER_STATUS'));//订单支付状态


         $this->display();
    }


    /**
     * 添加订单
     *
     * @return void
     * @author
     **/
    function add()
    {
        //查询购物车里面的数据
        //根据登陆的人，去查询他的订单
        $map['member_id']=$_SESSION['member']['id'];
        $map['endble']=0;//查询当前用户未生成订单的购物车商品
        $cart=D('Admin/cart')->relation(true)->where($map)->select();


        //组装订单数据
        $data['order_no']=date('YmdHis',time()).mt_rand(10000,99999);//订单编号
        $data['member_id']=$_SESSION['member']['id'];//订单所属人id

        $data['total_price']=0;//订单总价

        //循环购物车计算订单总价
        foreach ($cart as $key => $v) {
            //将数据统一存储到订单表的goods_desc字段里面
            //组装订单需要显示的购物车商品信息
            //商品名称
            $data['goods_desc'][$key]['goods_name']=$v['goods']['goods_name'];
            //商品单价
            $data['goods_desc'][$key]['shop_price']=$v['goods']['shop_price']+$v['spec_price']['spec_price'];
            //商品图片
            $data['goods_desc'][$key]['img']=$v['goods']['img'];
            //购买数量
            $data['goods_desc'][$key]['goods_num']=$v['goods_num'];

            //商品小计公式 (单价+规格单价)*数量
            $data['total_price']+=($v['goods']['shop_price']+$v['spec_price']['spec_price']*$v['goods_num']);
        }

        //因为数据库不能存储数组，因此需要进行转换，将数组转换成字符串
        // $data['goods_desc']=explode(',',$data['goods_desc']);
        // 将商品信息转成字符串格式存储到数据库中
        $data['goods_desc']=json_encode($data['goods_desc']);

        //实现订单添加
        $id=D('order')->add($data);
     // print_r($data);die;

        if ($id) {
           // $field['endble']=1;//逻辑删除下单成功，则购物车的商品就不应该存在了
           // //修改商品状态
           // D('Admin/cart')->where($map)->data($field)->save();


           //调用支付请求方法
           D('Home/pay_record')->buildRequestForm($data['order_no'],$data['total_price'],2,$_SESSION['member']['id'],$data['order_no']);

           // $this->success('下单成功',U('member/order/lists'));die;
        }else{
            // $this->error('下单失败','',2);die;
        }

    }

}